package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.UserRegisterBean;
import com.atguigu.gmall.realtime.commont.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.DorisUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2023/4/28 14:47
 */
public class Dws_05_DwsUserUserRegisterWindow_Doris extends BaseApp {
    public static void main(String[] args) {
        new Dws_05_DwsUserUserRegisterWindow_Doris().init(
            40005,
            2,
            "Dws_05_DwsUserUserRegisterWindow",
            Constant.TOPIC_DWD_USER_REGISTER
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("create_time"))  // fastjoin 会自动把日期变成 long 返回
                    .withIdleness(Duration.ofSeconds(60))
            )
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .aggregate(
                new AggregateFunction<JSONObject, Long, Long>() {
                    // 初始化一个累加器
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    
                    // 累加
                    @Override
                    public Long add(JSONObject value, Long acc) {
                        return acc + 1;
                    }
                    
                    // 返回聚合结果
                    @Override
                    public Long getResult(Long acc) {
                        return acc;
                    }
                    
                    // 合并累加器: 当窗口是 session 窗口才会触发
                    @Override
                    public Long merge(Long a, Long b) {
                        return a + b;
                    }
                },
                new ProcessAllWindowFunction<Long, UserRegisterBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<Long> elements,
                                        Collector<UserRegisterBean> out) throws Exception {
                        
                        Long count = elements.iterator().next();
                        
                        String stt = AtguiguUtil.tsToDateTime(ctx.window().getStart());
                        String edt = AtguiguUtil.tsToDateTime(ctx.window().getEnd());
                        out.collect(new UserRegisterBean(stt,
                                                         edt,
                                                         DateFormatUtil.toPartitionDate(ctx.window().getStart()),
                                                         count,
                                                         System.currentTimeMillis()
                        ));
                        
                        
                    }
                }
            )
            .map(bean -> {
                SerializeConfig config = new SerializeConfig();
                config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;  // 转成json的时候, 属性名使用下划线
                return JSON.toJSONString(bean, config);
            })
            .sinkTo(DorisUtil.getDorisSink("gmall.dws_user_user_register_window"));
        
    }
}
